<template>
    <div>
        <div v-if="currentPanel == 'list'">
            <!--添加按钮  搜索框-->
            <el-card style="height: 80px">
                <div>
                    <el-row>
                        <el-col :span="17">
                            <el-button type="primary" icon="el-icon-plus" @click="currentHandler('add')">
                                新建活码
                            </el-button>
                            <el-button type="primary" icon="el-icon-plus" @click="handleEdit()">新建分组
                            </el-button>
<!--                            <el-button size="small" type="primary" icon="el-icon-plus" @click="download">批量下载
                            </el-button>-->
                        </el-col>
                        <el-col :span="7">
                            <el-form :inline="true" :model="query">
                                <el-form-item>
                                    <el-input v-model="query.codeName"
                                              placeholder="输入活码名称"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" icon="el-icon-search" @click="search">查询
                                    </el-button>
                                    <el-button type="primary" icon="el-icon-plus" @click="resetQuery">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>
                </div>
            </el-card>
            <div class="interspaceH"></div>
            <el-row>
                <el-col :span="4">
                    <el-card class="box-card" style="width: 250px;height: 700px">
                        <!--树标题-->
                        <span>分组管理</span>
                        <!--下拉框-->
<!--                        <el-tree class="promotionList" :data="formData" @node-click="group"></el-tree>-->
                        <el-tree :data="data" :props="defaultProps" accordion @node-click="group">
                        <span class="custom-tree-node" slot-scope="{ node, data }"  @mouseover="data.show = true" @mouseleave="data.show = false">
                            <span>{{ node.label }}</span>
                            <span>
                                <el-button v-if="data.show" type="text" size="mini" @click="() => removeGroup(node, data)">
                                    删除
                                </el-button>
                            </span>
                        </span>
                        </el-tree>
<!--                            <div style="height: 10px"></div>
                            <div style="border: 2px">
                                <div v-for="(item, index) in formData" :key="index" @click="group(item)" style="padding: 10px 0;cursor:pointer">{{ item.codeGroupName }}</div>
                            </div>-->
                    </el-card>
                </el-col>
                <el-col :span="20">
                    <el-card class="box-card" style="width: 1360px;height: 700px">
                        <!--表格-->
                        <el-col>
                            <el-table @selection-change="tableRowChange" :data="listData"
                                      :header-cell-style="{background:'#F3F4F7',color:'#555'}" style="width: 100%">
                                <el-table-column align="center" type="selection" width="50px">
                                </el-table-column>
                                <el-table-column prop="codeName" label="活码名称">
                                </el-table-column>
<!--                              <el-table-column prop="codeGroupName" label="分组">
                              </el-table-column>-->
                              <el-table-column label="活码引流成员">
                                  <template slot-scope="scope">
                                      <el-button type="text" @click="chakan(scope.row)">查看</el-button>
                                  </template>

                              </el-table-column>

                                <el-table-column prop="tags" label="标签" >
                                    <template slot-scope="scope">
                                        <div :key="index" v-for="(item, index) in scope.row.tagList">
                                            <el-tag v-if="item != null && item != ''" :disable-transitions="false"
                                                    style="margin-right: 10px">
                                                    {{ item }}
                                            </el-tag>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="createTime" label="创建时间">
                                    <template slot-scope="scope">
                                        <div>{{ scope.row.createTime }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column align="center" label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="tui(scope.row)">推广</el-button>
                                        <el-button type="text" @click="updateGroup(scope.row)">编辑</el-button>
                                        <el-button type="text" @click="detailHandle(scope.row)">详情</el-button>
                                        <el-button type="text" @click="download(scope.row)">下载</el-button>
<!--                                        <el-button type="text" @click="deletes(scope.row)">删除</el-button>-->
<!--                                        <el-button type="text">更多</el-button>-->
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!--分页-->
                            <el-pagination @size-change="queryDataHandle(pagePagination.currentPage,$event)"
                                           @current-change="queryDataHandle($event,pagePagination.pageSize)"
                                           :current-page="pagePagination.currentPage"
                                           :page-sizes="pagePagination.pageSizes" :page-size="pagePagination.pageSize"
                                           layout="total, sizes, prev, pager, next"
                                           :total="pagePagination.total">
                            </el-pagination>
                        </el-col>
                    </el-card>
                </el-col>
            </el-row>
          <!--活码引流成员-->
          <el-dialog title="活码引流成员" :visible.sync="people" width="70%" :close-on-click-modal="false">
            <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="weekDayName" label="工作周期" >
                </el-table-column>
                <el-table-column prop="triggerTime" label="在线时间" >
                </el-table-column>
                <el-table-column prop="empName" label="员工" >
                </el-table-column>
            </el-table>
          </el-dialog>
            <!-- 编辑界面 -->
            <el-dialog :title="title" :visible.sync="editFormVisible" :rules="rules" width="30%" :close-on-click-modal="false">
                <el-form ref="form" :rules="rules" :model="editForm" label-width="80px">
                    <el-form-item label="活码分组名称" prop="codeGroupName" label-width="120px">
                        <el-input v-model="editForm.codeGroupName" placeholder="填写活码分组名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" class="title" @click="submitForm">保存</el-button>
                        <el-button @click="editFormVisible = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog title="推广" :visible.sync="tuiguang" width="30%" :close-on-click-modal="false">
                <el-form ref="form" :model="table" label-width="90px">
                    <el-form-item>
                        <el-image style="width: 100px; height: 100px" :src="table.codeUrl" fit="fill"
                                  :preview-src-list="materialTrackTypeMax"></el-image><br/>
                        <el-button size="small" class="title" @click="xiazai(table.codeUrl)">下载二维码</el-button>
                        <el-button size="small" @click="fuzhi(table.codeUrl)">复制链接</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog title="编辑活码" :visible.sync="updateGroups" width="30%" :close-on-click-modal="false">
                <el-form ref="form" :model="editGroup" label-width="90px">
                    <el-form-item>
                        <el-select v-model="editGroup.codeGroupId" placeholder="请选择">
                            <el-option v-for="item in formData" :key="item.id" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="updateGroups = false">取消</el-button>
                        <el-button @click="edits">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

        </div>
        <div v-if="currentPanel == 'add'">
            <employeeAdd :codeInfo="singer" @currentHandler=currentHandler></employeeAdd>
        </div>
        <div v-if="currentPanel == 'view'">
            <employeeView :codeInfo="singer" @currentHandler=currentHandler></employeeView>
        </div>
    </div>
</template>

<script>
import Pagination from '@/components/Pagination'

import employeeAdd from "@/views/masket/code/add"
import employeeView from '@/views/masket/code/view'

export default {
    // 注册组件
    components: {
        Pagination,
        employeeAdd,
        employeeView
    },
    data() {
        return {
            formData: [],
            singer: {},
            data: [],
            tableData: [],
            people: false,
            tuiguang: false,
            table: {},
            currentPanel: 'list',
            //tree
            updateGroups: false,
            editGroup: {},
            query: {
                codeName: ''
            },

            defaultProps: {
                label: 'codeGroupName'
            },

            nshow: true, //switch开启
            fshow: false, //switch关闭
            loading: false, //是显示加载
            editFormVisible: false, //控制编辑页面显示与隐藏
            title: '添加',
            editForm: {
                deptId: '',
                codeGroupName: '',
                token: localStorage.getItem('logintoken')
            },
            // rules表单验证
            rules: {
                codeName: [
                    {required: true, message: '请输入活码分组名称', trigger: 'blur'}
                ]
            },
            listData: [], //用户数据
            // 分页参数
            pagePagination: {
                currentPage: 1,
                pageSizes: [10, 15, 20, 25],
                pageSize: 10,
                total: 0
            },
        }
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */

    mounted() {
        this.queryDataHandle(1, 10)

    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
        queryDataHandle(page = 1, row = 10) {
            let payload = {
                pageNum: page,
                pageSize: row
            }
            let that = this
            that.$request("/api/code/getByEmpCodeName/1_0", payload, "POST").then((data) => {
                that.pagePagination['total'] = data.total
                that.pagePagination['pageSize'] = data.row
                that.listData = data.rows
            })

            that.$request("/api/codeGroup/selectCodeGroup/1_0", {}, "POST").then((data) => {
                for (let item of data.rows){
                    item['show'] = false
                    that.data.push(item)
                }
                that.formData = data.rows
            })

        },
        detailHandle(row) {
            this.singer = row
            this.currentPanel = 'view'
        },
        updateGroup(row) {
            this.editGroup = row
            this.updateGroups = true
        },
        //修改分组
        edits() {
            let code = {
                codeGroupId: this.editGroup.codeGroupId,
                codeId: this.editGroup.codeId
            }
            this.$request("/api/code/saveEmpCode/1_0", code, "POST").then((data) => {
                this.formData = data.data
                if (this.formData == 1){
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                }else {
                    this.$message({
                        message: '修改失败',
                        type: 'error'
                    });
                }
            })
        },
        //删除分组
        removeGroup(node, data) {
            //let that = this
            //that.isDelete = true
            this.$confirm('此操作将永久删除该分组, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let codeGroupId = data.codeGroupId
                this.$request('/api/code/getByCodeGroupId/1_0?codeGroupId=' + codeGroupId, '', 'POST').then((data) => {
                    if (data.rows != null && data.rows.length !== 0){
                        this.$message.error('请先将该分组中数据清空后再删除！')
                    }else {
                        this.$request('/api/codeGroup/delete/1_0?id=' + codeGroupId, '', 'POST').then((data) => {
                            this.data = []
                            this.$message.success('删除成功！')
                            this.queryDataHandle(1, 10)
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '已取消',
                    type: 'info'
                });
            });
        },

        chakan(row) {
          var code = {
              codeId : row.codeId
          }
          this.people = true
          let that = this
          this.$request("/api/code/getByUserName/1_0", code, "POST").then((data) => {
              let list = data.rows

              list.map((item) => {
                  switch (item.weekDay) {
                      case "1":
                          item.weekDayName = "星期日"
                          break;
                      case "2":
                          item.weekDayName = "星期一"
                          break;
                      case "3":
                          item.weekDayName = "星期二"
                          break;
                      case "4":
                          item.weekDayName = "星期三"
                          break;
                      case "5":
                          item.weekDayName = "星期四"
                          break;
                      case "6":
                          item.weekDayName = "星期五"
                          break;
                      case "7":
                          item.weekDayName = "星期六"
                          break;
                  }
              })
              that.tableData = list
          })
        },

        tui(row) {
            this.table = row
            this.tuiguang = true
        },
        fuzhi(data) {
            let url = data;
            let oInput = document.createElement('input');
            oInput.value = url;
            document.body.appendChild(oInput);
            oInput.select(); // 选择对象;
            document.execCommand("Copy"); // 执行浏览器复制命令
            this.$message({
                message: '复制成功！',
                type: 'success'
            });
            oInput.remove()
        },
        xiazai(url) {
            let that = this;
                 let hreLocal="";
                 hreLocal = url;
                 this.downloadByBlob(hreLocal,"员工活码.jpg")
            //this.$requestFile("/api/code/downloadFile/1_0", {accessoriesAddress:url},"员工活码.jpg")
         },
        downloadByBlob(url,name) {
             let image = new Image()
             image.setAttribute('crossOrigin', 'anonymous')
             image.src = url
             image.onload = () => {
                   let canvas = document.createElement('canvas')
                   canvas.width = image.width
                   canvas.height = image.height
                   let ctx = canvas.getContext('2d')
                   ctx.drawImage(image, 0, 0, image.width, image.height)
                   canvas.toBlob((blob) => {
                         let url = URL.createObjectURL(blob)
                           let eleLink = document.createElement('a')
                           eleLink.download = name
                           eleLink.href = url
                           eleLink.click()
                           eleLink.remove()

                         // 用完释放URL对象
                         URL.revokeObjectURL(url)
                       })
                 }
           },

        group(item){
            let that = this
            this.codeGroupId = item.codeGroupId
            this.$request("/api/code/getByCodeGroupId/1_0?codeGroupId=" + this.codeGroupId, '', "POST").then((data) => {
                that.listData = data.rows
            })
        },
        //新建活码跳转
        currentHandler(type) {
            if (this.formData.length > 0){
                this.currentPanel = type
                this.queryDataHandle(1, 10);
            }else {
                this.$message({
                    message: '未添加分组',
                    type: 'error'
                });
            }

        },
        resetQuery() {
            this.query = {}
            this.queryDataHandle(1, 10)
        },
        // 分页插件事件
        // 搜索事件
        search() {
            var code = {
                codeName : this.query.codeName
            }
            this.$request("/api/code/getByEmpCodeName/1_0", code , "POST").then((data) => {
                this.listData = data.rows
                // this.getdata(this.formInline ),
                    this.$message({
                        message: '查询成功',
                        type: 'success'
                    });
            })


        },
        //显示编辑界面
        handleEdit: function (index, row) {
            this.editFormVisible = true
            if (row != undefined && row != 'undefined') {
                this.title = '修改'
                this.editForm.deptId = row.deptId
                this.editForm.codeGroupName = row.codeGroupName
                this.editForm.deptNo = row.deptNo
            } else {
                this.title = '新建活码分类'
                this.editForm.deptId = ''
                this.editForm.codeGroupName = ''
                this.editForm.deptNo = ''
            }
        },
        download(row) {
            let url = row.codeUrl;
            let hreLocal="";
            hreLocal = url;
            this.downloadByBlob(hreLocal,"员工活码.jpg")
        },
        //删除
        deletes(row) {
            this.$confirm('确定要删除吗?', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    let code = row
                    this.$request("/api/code/deletes/1_0", code , "DELETE").then((data) => {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.queryDataHandle(this.pagePagination.currentPage, this.pagePagination.pageSize)
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },
        // 编辑、增加页面保存方法
        submitForm() {
          var codeGroup = {
              codeGroupName : this.editForm.codeGroupName
          }
            this.$request("/api/codeGroup/addCodeGroup/1_0", codeGroup , "POST").then((data) => {
                this.$message({
                    message: '保存成功',
                    type: 'success'
                });
                this.data = []
                this.queryDataHandle(1, 10)
            })

            this.editFormVisible = false

        },
        callFather(parm) {
            this.formInline.page = parm.currentPage
            this.formInline.limit = parm.pageSize
            this.getdata(this.formInline)
        },

        // 关闭编辑、增加弹出框
        closeDialog() {
            this.editFormVisible = false
        },
        tableRowChange(val) {
            if (val.length > 0) {
                this.titleCurrentPanel = true
            } else {
                this.titleCurrentPanel = false
            }
            this.multipleSelection = val;
        },
    },
    computed: {
        materialTrackTypeMax() {
            return [this.table.codeUrl]
        },
    }
}
</script>

<style scoped>
.el-divider--vertical {
    display: inline-block;
    width: 1px;
    height: 7em;
    margin: 0 8px;
    vertical-align: middle;
    position: relative;
}
.promotionList .el-tree-node {
    white-space: nowrap;
    outline: 0;
    padding-top: 10px;
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>



